package org.example.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.annotation.TableName;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.example.config.AlipayConts;
import org.example.config.R;
import org.example.domain.Page;
import org.example.domain.Zero;
import org.example.servide.ZeroService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("zero")
public class ZeroController {
    @Autowired
    ZeroService zeroService;

    @Autowired
    HttpServletRequest request;


    @RequestMapping("add")
    public R add(Zero zero){
        boolean b = zeroService.addZero(zero);
        return R.successed(b);
    }

    @RequestMapping("list")
    public R list( Page page,String tradeName){
        PageHelper.startPage(page.getPageNum(),page.getPageSize());
        List<Zero> list = zeroService.lists(tradeName);
        PageInfo<Zero> zeroPageInfo = new PageInfo<>(list);
        return R.successed(zeroPageInfo);
    }



    @RequestMapping("topayok")
    public R topay(Zero zero){
        Zero id = zeroService.getId(zero.getId());
        if(id!=null){
            zero.setTotalPrice(zero.getPrice().multiply(new BigDecimal(zero.getNum()+"")));
            zeroService.updateZerototal(zero);
            return R.successed("修改成功");
        }

        return R.successed("修改失败");
    }



    @RequestMapping("toPay")
    public R toPay(@RequestBody String outTradeNo) throws AlipayApiException {
        Zero zero = zeroService.getZero(outTradeNo);
        AlipayClient alipayClient = AlipayConts.ALIPAY_CLIENT;
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
//异步接收地址，仅支持http/https，公网可访问
        request.setNotifyUrl("");
//同步跳转地址，仅支持http/https
        request.setReturnUrl("");
/******必传参数******/
        JSONObject bizContent = new JSONObject();
//商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", zero.getOutTradeNo());
//支付金额，最小值0.01元
        bizContent.put("total_amount", zero.getTotalPrice());
//订单标题，不可使用特殊符号
        bizContent.put("subject", zero.getTradeName());
//电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

/******可选参数******/
//bizContent.put("time_expire", "2022-08-01 22:00:00");

//// 商品明细信息，按需传入
//JSONArray goodsDetail = new JSONArray();
//JSONObject goods1 = new JSONObject();
//goods1.put("goods_id", "goodsNo1");
//goods1.put("goods_name", "子商品1");
//goods1.put("quantity", 1);
//goods1.put("price", 0.01);
//goodsDetail.add(goods1);
//bizContent.put("goods_detail", goodsDetail);

//// 扩展信息，按需传入
//JSONObject extendParams = new JSONObject();
//extendParams.put("sys_service_provider_id", "2088511833207846");
//bizContent.put("extend_params", extendParams);

        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request,"POST");
// 如果需要返回GET请求，请使用
// AlipayTradePagePayResponse response = alipayClient.pageExecute(request,"GET");
        String pageRedirectionData = response.getBody();
        System.out.println(pageRedirectionData);

        if(response.isSuccess()){
            System.out.println("调用成功");
            return R.successed(pageRedirectionData);
        } else {
            System.out.println("调用失败");
            return R.failed("拉起支付失败");
        }
    }


    @RequestMapping("callback")
    public void callback() throws AlipayApiException {
        Map<String, String> paramMap = ServletUtil.getParamMap(request);

        boolean b = AlipaySignature.rsaCheckV1(paramMap, AlipayConts.ALIPAY_PUBLIC_KEY, AlipayConts.CHARSET, AlipayConts.SIGN_TYPE);
        if(b && StrUtil.equalsIgnoreCase(paramMap.get("trade_status"),AlipayConts.TRADE_SUCCESS)){
            String outTradeNo = paramMap.get("out_trade_no");
            String tradeNo = paramMap.get("trade_no");
            String totalAmount = paramMap.get("total_amount");
            zeroService.docallback(outTradeNo,tradeNo,new BigDecimal(totalAmount));
        }
    }


    @RequestMapping("refund")
    public R refund(@RequestBody String outTradeNo) throws AlipayApiException {
        Zero zero = zeroService.getZero(outTradeNo);
        AlipayClient alipayClient = AlipayConts.ALIPAY_CLIENT;
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", outTradeNo);
        bizContent.put("refund_amount", zero.getTotalPrice());
        bizContent.put("out_request_no", "HZ01RF001");

//// 返回参数选项，按需传入
//JSONArray queryOptions = new JSONArray();
//queryOptions.add("refund_detail_item_list");
//bizContent.put("query_options", queryOptions);

        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
            return R.successed("退款成功");
        } else {
            System.out.println("调用失败");
            return R.failed("退款失败");
        }
    }
}
